<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page contentType="text/html;charset=UTF-8"%>
<%@ page import="down2.*" %>
<%@ page import="java.net.URLDecoder" %>
<%@ page import="java.net.URLEncoder" %>
<%@ page import="org.apache.commons.lang.*" %>
<%@ page import="com.google.gson.FieldNamingPolicy" %>
<%@ page import="com.google.gson.Gson" %>
<%@ page import="com.google.gson.GsonBuilder" %>
<%@ page import="com.google.gson.annotations.SerializedName" %>
<%@ page import="java.io.*" %>
<% out.clear();
/*
	下载数据库中的文件。
	更新记录：
		2015-05-13 创建
		2017-12-09 完善Range协议
*/
String fileName = "网易云音乐.exe";//客户端保存的文件名
String filePath = "d:\\文件校验工具.exe";//路径

fileName = URLEncoder.encode(fileName,"UTF-8");
fileName = fileName.replaceAll("\\+","%20");
response.setContentType("application/octet-stream;charset:utf-8");
response.addHeader("Content-Disposition","attachment;filename=" + fileName);
response.addHeader("Pragma", "No-cache");
response.addHeader("Cache-Control", "No-cache");
response.addHeader("Expires", "0");

//定位文件块索引
File f = new File(filePath);
long fileLen = f.length();
long blockSize = fileLen;//块大小
long blockBegin = 0;
long blockEnd = 0;
RandomAccessFile raf = new RandomAccessFile(filePath,"r");
FileInputStream in = new FileInputStream( raf.getFD() );
String range = request.getHeader("Range");
if(range != null)
{
	//清除bytes=
	int pos = range.indexOf("=");
	if(pos != -1) range = range.substring(pos+1);
	
	/*
		1-
		-1
		0-1
	*/
	String[] rs = range.split("-");//bytes=10254
	//-1
	if( StringUtils.isEmpty(rs[0]) )
	{
		blockSize = Long.parseLong(rs[1]);
		in.skip(fileLen - blockSize);
		blockEnd = fileLen - 1;
		blockBegin = fileLen - blockSize;
	}//1-
	else if( StringUtils.isEmpty(rs[1]))
	{
		blockBegin = Long.parseLong(rs[0]);
		in.skip(blockBegin);
		blockSize = fileLen - blockBegin;
		blockEnd = (blockBegin + blockSize) - 1;
	}//1-1
	else
	{
		blockBegin = Long.parseLong(rs[0]);
		blockEnd = Long.parseLong(rs[1]);
		blockSize = (blockEnd - blockBegin) + 1;
		in.skip(blockBegin);
	}
}
response.addHeader("Content-Length",Long.toString(blockSize));
response.addHeader("Content-Range",String.format("bytes %d-%d/%d",blockBegin,blockEnd,fileLen) );

int sizeR = 1048576;//一次读1MB数据，如果服务器内存足够，可适当调大尺寸。
byte[] b = new byte[sizeR];
int i = 0;
OutputStream outp = response.getOutputStream();
while(blockSize>0)
{
	if(blockSize < sizeR) sizeR = (int)blockSize;
	int readed = in.read(b,0,sizeR);	
	outp.write(b, 0, readed);
	blockSize -= readed;
}
outp.flush();

in.close();
outp.close();
in 	 = null;
outp = null;
%>